package com.etxxy.remoting.service;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.etxxy.common.json.JSON;
import com.etxxy.common.security.BlowfishPropertiesFactory;
import com.etxxy.remoting.dto.SmsRequestDTO;

/**
 * @category 短信操作
 * @author yiz
 *
 */
public class MsgSenderServiceImpl implements SmsSenderService {

	private static final Logger logger = LoggerFactory.getLogger(MsgSenderServiceImpl.class);

	@Autowired
	private VelocityEngine velocityEngine; // 模板解析
	@Value("${sms.wsdl.url}")
	private String wsdlUrl;

	@Value("${sms.production}")
	private String production;
	@Value("${sms.username}")
	private String username;
	@Value("${sms.password}")
	private String password;

	@Override
	public Map<String, Object> sendSms(SmsRequestDTO smsRequestDTO) {
		logger.debug("短信请求参数smsRequestDTO={}", JSON.toJSONString(smsRequestDTO));
		String templateContent = smsRequestDTO.getTemplate();
		Map<String, Object> datas = smsRequestDTO.getData();
		String content = getContent(templateContent, datas);
		logger.debug("短信发送内容content={}", content);
		Boolean isProduction = false;
		if (StringUtils.isNotBlank(production) && "true".equals(production)) {
			isProduction = Boolean.valueOf(production);
		}
		if (isProduction) {
			try {
				password = BlowfishPropertiesFactory.decode(password);
			} catch (Exception e) {
				logger.error("解密短信密码e={}", e);
			}
		}
		return null;
	}

	/**
	 * @category 得到发送短信的真实内容
	 * @return
	 */
	private String getContent(String templateContent, Map<String, Object> datas) {
		StringWriter writer = null;
		try {

			writer = new StringWriter();
			VelocityContext context = new VelocityContext(datas);

			velocityEngine.evaluate(context, writer, "", templateContent);

			return writer.toString();
		} catch (VelocityException e) {
			logger.error(" VelocityException : " + templateContent + "\n" + e);
		} catch (IOException e) {
			logger.error(" IOException : " + templateContent + "\n" + e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					logger.error("###StringWriter close error ... e={}", e);
				}
			}
		}
		return null;
	}

}
